# db_config.py
import pymysql

class DBConfig:
    # 数据库连接配置
    config = {
        'host': 'localhost',
        'port': 3306,
        'user': 'root',
        'password': '1234',
        'database': 'stock',
        'charset': 'utf8mb4'
    }

    @classmethod
    def get_connection(cls):
        """获取数据库连接"""
        return pymysql.connect(
            host=cls.config['host'],
            port=cls.config['port'],
            user=cls.config['user'],
            password=cls.config['password'],
            database=cls.config['database'],
            charset=cls.config['charset'],
            cursorclass=pymysql.cursors.DictCursor  # 可选，返回字典
        )

    @classmethod
    def execute_sql(cls, sql, params=None, fetch=False):
        """执行SQL语句，可支持单条或批量操作"""
        conn = cls.get_connection()
        try:
            with conn.cursor() as cursor:
                if fetch:
                    cursor.execute(sql, params)
                    return cursor.fetchall()
                elif isinstance(params, list) and len(params) > 0 and isinstance(params[0], dict):
                    # ✅ 批量插入：List[Dict]
                    cursor.executemany(sql, params)
                else:
                    # ✅ 单条插入或无参数
                    cursor.execute(sql, params)
                conn.commit()
                return cursor.rowcount
        except Exception as e:
            conn.rollback()
            print(f"SQL 执行失败: {e}")
            raise
        finally:
            conn.close()
